package com.xiaohudie.JUC;

/**
 * @Author xiao hu die
 * @Date 2022/1/15 15:42
 * @Version 1.0
 */

import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**读写锁的演示案例*/
class Resource{
     private volatile  Map<String,Object> map =new HashMap<>();
     /**new一个读写锁*/
     private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    /**写方法*/
    @SneakyThrows
    public void write(String key, Object value){
        /**新加一个写锁*/
        readWriteLock.writeLock().lock();

        System.out.println(Thread.currentThread().getName()+"正在加数据");

        TimeUnit.SECONDS.sleep(new Random().nextInt(5));
        map.put(key, value);
        System.out.println(Thread.currentThread().getName()+"写完了数据");
        /**写完之后释放锁*/
        readWriteLock.writeLock().unlock();
    }
    /**读方法*/
    @SneakyThrows
    public Object read(String key){
        /**新加一个读锁方法*/
        readWriteLock.readLock().lock();
        System.out.println(Thread.currentThread().getName()+"正在读数据");

        TimeUnit.SECONDS.sleep(new Random().nextInt(5));
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读出来了数据"+key);
         /**将读锁释放掉*/
         readWriteLock.readLock().unlock();
       return  o;
    }
}
public class Thread11 {
    public static void main(String[] args) {
        Resource resource1 =new Resource();
        for (int i = 0; i < 5; i++) {
            final  int num =i;
            new Thread(()->{
                resource1.write(String.valueOf(num),num);
            },String.valueOf(i)).start();
        }
        for (int i = 0; i < 5; i++) {
            final  int num =i;
            new Thread(()->{
                resource1.read(String.valueOf(num));
            },String.valueOf(i)).start();
        }
    }
}
